package com.example.esp8266.Equipment.Equipment_Fragment;

import android.animation.ObjectAnimator;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.LinearInterpolator;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import com.example.esp8266.Equipment.Fragment_CallBack;
import com.example.esp8266.R;


import java.util.Objects;

public class Fan_Fragment extends Fragment
        implements View.OnClickListener{
    private View root;
    private String target_device,back_info;
    private Fragment_CallBack callback;
    private TextView tvSpeedValue_1,tvSpeedValue_2,fan1_state,fan2_state;
    private ObjectAnimator rotationAnimator_1,rotationAnimator_2;
    private boolean Fan1_status = false,Fan2_status = false;
    private int progress_1 = 0, progress_2 = 0;
    private int states = 0;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 获取传递的数据
        Bundle args = getArguments();
        if (args != null) {
            target_device = args.getString("target_device", "");//目标控制设备
            back_info = args.getString("back_info","");//返回上一层标识
        }

        // 检查 getActivity() 是否返回的对象为非空
        if (getActivity() != null) {
            // 获取 SharedPreferences 对象
            SharedPreferences sharedPreferences = getActivity().getSharedPreferences("my_prefs", Context.MODE_PRIVATE);
            Fan1_status = sharedPreferences.getBoolean("Fan1_states", false);
            Fan2_status = sharedPreferences.getBoolean("Fan2_states", false);
            progress_1 = sharedPreferences.getInt("Fan1_speed",0);
            progress_2 = sharedPreferences.getInt("Fan2_speed",0);
            SharedPreferences.Editor editor = sharedPreferences.edit();
            editor.putString("previous_page",back_info);
            editor.apply();
        } else {
            Log.e("Fragment", "getActivity() returned null");
            // 可以选择在这里处理 getActivity() 返回 null 的情况，例如显示错误信息或采取其他操作
        }

    }

    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        if (context instanceof Fragment_CallBack) {
            callback = (Fragment_CallBack) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement Fragment_CallBack");
        }
    }

    @SuppressLint("SetTextI18n")
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        root = inflater.inflate(R.layout.fan_control_fragment, container, false);

        View btn8 = root.findViewById(R.id.fan_xml_btn8);
        btn8.setOnClickListener(this);

        View btn9 = root.findViewById(R.id.fan_xml_btn9);
        btn9.setOnClickListener(this);

        // 获取布局中的控件
        SeekBar seekBarSpeed_1 = root.findViewById(R.id.seekBar_speed_1);
        seekBarSpeed_1.setProgress(progress_1);
        tvSpeedValue_1 = root.findViewById(R.id.fan_speed_text_1);
        tvSpeedValue_1.setText(progress_1 + "%");

        SeekBar seekBarSpeed_2 = root.findViewById(R.id.seekBar_speed_2);
        seekBarSpeed_2.setProgress(progress_2);
        tvSpeedValue_2 = root.findViewById(R.id.fan_speed_text_2);
        tvSpeedValue_2.setText(progress_2 + "%");

        fan1_state = root.findViewById(R.id.fan1_state_text);
        fan2_state = root.findViewById(R.id.fan2_state_text);

        ImageView fan_1 = root.findViewById(R.id.img_fan1);
        ImageView fan_2 = root.findViewById(R.id.img_fan2);

        if(Fan1_status) {
            fan1_state.setText("运行");
            fan1_state.setTextColor(Color.parseColor("#00FA9A"));
            fan_1.setImageDrawable(ContextCompat.getDrawable(requireContext(), R.drawable.fan_on));
        }
        if(Fan2_status) {
            fan2_state.setText("运行");
            fan2_state.setTextColor(Color.parseColor("#00FA9A"));
            fan_2.setImageDrawable(ContextCompat.getDrawable(requireContext(), R.drawable.fan_on));
        }

        rotationAnimator_1 = ObjectAnimator.ofFloat(fan_1, "rotation", 0f, 360f);
        rotationAnimator_1.setDuration(0);
        if (Fan1_status) rotationAnimator_1.setDuration(2000 - (progress_1 * 15L));
        rotationAnimator_1.setInterpolator(new LinearInterpolator());
        rotationAnimator_1.setRepeatCount(ObjectAnimator.INFINITE);
        rotationAnimator_1.start();

        rotationAnimator_2 = ObjectAnimator.ofFloat(fan_2, "rotation", 0f, 360f);
        rotationAnimator_2.setDuration(0);
        if (Fan2_status) rotationAnimator_2.setDuration(2000 - (progress_2 * 15L));
        rotationAnimator_2.setInterpolator(new LinearInterpolator());
        rotationAnimator_2.setRepeatCount(ObjectAnimator.INFINITE);
        rotationAnimator_2.start();

        seekBarSpeed_1.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @SuppressLint("SetTextI18n")
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                // change
                tvSpeedValue_1.setText(progress + "%");

            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                // stop
                String message_1 = callback.getMsgFromActivity("Request Message");
                if (message_1 != null && (message_1.contains("offline") || message_1.contains("busy"))) {
                    return;
                }
                progress_1 = seekBar.getProgress();
                int duration = 2000 - progress_1 * 15;
                if (progress_1 < 20) {
                    progress_1 = 0;
                    duration = 0;
                    Fan1_status = false;
                    fan1_state.setText("停转");
                    fan1_state.setTextColor(Color.parseColor("#FF0022"));
                    fan_1.setImageDrawable(ContextCompat.getDrawable(requireContext(), R.drawable.fan_off));
                }
                else {
                    Fan1_status = true;
                    fan1_state.setText("运行");
                    fan1_state.setTextColor(Color.parseColor("#00FA9A"));
                    fan_1.setImageDrawable(ContextCompat.getDrawable(requireContext(), R.drawable.fan_on));
                }
                rotationAnimator_1.setDuration(duration);
                rotationAnimator_1.start();
                if (states == 0) {
                    sendMessageToActivity("Fan1.Speed(" + progress_2 +").001");
                } else if (states == 1) {
                    sendMessageToActivity("Fan1.Speed(" + progress_2 +").010");
                } else if (states == 2) {
                    sendMessageToActivity("Fan1.Speed(" + progress_2 +").100");
                }
            }
        });

        seekBarSpeed_2.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @SuppressLint("SetTextI18n")
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                // change
                tvSpeedValue_2.setText(progress + "%");
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                // stop
                String message_2 = callback.getMsgFromActivity("Request Message");
                if (message_2 != null && (message_2.contains("offline") || message_2.contains("busy"))) {
                    return;
                }
                progress_2 = seekBar.getProgress();

                int duration = 2000 - progress_2 * 15;
                if (progress_2 < 20) {
                    progress_2 = 0;
                    duration = 0;
                    Fan2_status = false;
                    fan2_state.setText("停转");
                    fan2_state.setTextColor(Color.parseColor("#FF0022"));
                    fan_2.setImageDrawable(ContextCompat.getDrawable(requireContext(), R.drawable.fan_off));
                }
                else {
                    Fan2_status = true;
                    fan2_state.setText("运行");
                    fan2_state.setTextColor(Color.parseColor("#00FA9A"));
                    fan_2.setImageDrawable(ContextCompat.getDrawable(requireContext(), R.drawable.fan_on));
                }
                rotationAnimator_2.setDuration(duration);
                rotationAnimator_2.start();
                if (states == 0) {
                    sendMessageToActivity("Fan2.Speed(" + progress_2 +").001");
                } else if (states == 1) {
                    sendMessageToActivity("Fan2.Speed(" + progress_2 +").010");
                } else if (states == 2) {
                    sendMessageToActivity("Fan2.Speed(" + progress_2 +").100");
                }
            }
        });

        return root;
    }

    @Override//调用OnClickListener接口处理各种单击事件
    public void onClick(View v) {
        if (v.getId() == R.id.fan_xml_btn8){
            if (Objects.equals(back_info, "MainControlFragment")){
                // 检查 getActivity() 是否返回的对象为非空
                if (getActivity() != null) {
                    // 获取 SharedPreferences 对象
                    SharedPreferences sharedPreferences = getActivity().getSharedPreferences("my_prefs", Context.MODE_PRIVATE);
                    SharedPreferences.Editor editor = sharedPreferences.edit();
                    editor.putString("previous_page",null);
                    editor.apply();
                } else {
                    Log.e("Fragment", "getActivity() returned null");
                    // 可以选择在这里处理 getActivity() 返回 null 的情况，例如显示错误信息或采取其他操作
                }
                MainControl_Fragment mainControlFragment = new MainControl_Fragment();
                replaceFragment(mainControlFragment);
            }
        } else if (v.getId() == R.id.fan_xml_btn9) {  // 切换功能场景
            states ++;
            if (states == 3) states = 0;
            if (states == 0){
                TextView states_text = root.findViewById(R.id.fan_title_text);
                states_text.setText("设备功能-客厅");
            } else if (states == 1) {
                TextView states_text = root.findViewById(R.id.fan_title_text);
                states_text.setText("设备功能-卧室");
            } else if (states == 2) {
                TextView states_text = root.findViewById(R.id.fan_title_text);
                states_text.setText("设备功能-厨房");
            }
        }
    }

    //动态切换视图
    private void replaceFragment(Fragment fragment){
        if (getActivity() != null) {
            FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
            FragmentTransaction transaction = fragmentManager.beginTransaction();
            transaction.replace(R.id.control_fragment_view, fragment);
            transaction.commit();
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        // 在离开 MainFragment 时
        // 检查 getActivity() 是否返回的对象为非空
        if (getActivity() != null) {
            // 获取 SharedPreferences 对象
            SharedPreferences sharedPreferences = getActivity().getSharedPreferences("my_prefs", Context.MODE_PRIVATE);
            SharedPreferences.Editor editor = sharedPreferences.edit();
            editor.putBoolean("Fan1_states",Fan1_status);
            editor.putBoolean("Fan2_states",Fan2_status);
            editor.putInt("Fan1_speed",progress_1);
            editor.putInt("Fan2_speed",progress_2);
            editor.apply();
        } else {
            Log.e("Fragment", "getActivity() returned null");
            // 可以选择在这里处理 getActivity() 返回 null 的情况，例如显示错误信息或采取其他操作
        }
        callback = null;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        // 在 Fragment 生命周期结束时执行的操作
        callback = null;
    }

    // 调用 callback 方法
    // 向Activity发数据
    private void sendMessageToActivity(String msg) {
        if (callback != null) {
            callback.sendMsgToActivity(msg);
        }
    }

    // 向Activity取数据
    private void receiveMessageFromActivity() {
        if (callback != null) {
            String message = callback.getMsgFromActivity("Request Message");
            Log.d("YourFragmentClass", "Message from Activity: " + message);
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        callback = null;
    }
}